package com.nari.ncps.screen.service.impl.ne;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.al.AlProdoperPrdSit;
import com.nari.ncps.screen.entity.ne.NeProdoperPowerGs;
import com.nari.ncps.screen.mapper.ne.NeProdoperSalesPurchaseMapper;
import com.nari.ncps.screen.service.ne.NeProdoperSalesPurchaseService;
import com.nari.ncps.screen.vo.ne.NePowerGenerationAnnualVO;
import com.nari.ncps.screen.vo.ne.NeSalesPurchaseVO;
import com.nari.ncps.screen.entity.ne.NeProdoperSalesPurchase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 购网电量和购网电价表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class NeProdoperSalesPurchaseServiceImpl extends ServiceImpl<NeProdoperSalesPurchaseMapper, NeProdoperSalesPurchase> implements NeProdoperSalesPurchaseService {

    @Autowired
    private NeProdoperSalesPurchaseMapper neProdoperSalesPurchaseMapper;

    @Override
    public List<NeSalesPurchaseVO> getSalesPurchase(Integer year) {

        // 如果没有指定年份，使用当前年份
//        if (year == null) {
//            year = LocalDate.now().getYear();
//        }
        YearMonth currentYearMonth = YearMonth.now();
        String current = currentYearMonth.format(DateTimeFormatter.ofPattern("yyyyMM"));

        // 获取12个月之前的年月
        YearMonth twelveMonthsAgo = YearMonth.now().minusMonths(11);
        String startDate = twelveMonthsAgo.format(DateTimeFormatter.ofPattern("yyyyMM"));

        LambdaQueryWrapper<NeProdoperSalesPurchase> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(NeProdoperSalesPurchase::getOrgCode, "100360")
                .ge(NeProdoperSalesPurchase::getStatisticTime, startDate)
                .le(NeProdoperSalesPurchase::getStatisticTime, current)
                .orderByAsc(NeProdoperSalesPurchase::getStatisticTime);
        List<NeProdoperSalesPurchase> dataList = this.list(wrapper);
        
        // 如果数据库查询结果为空，返回空列表
        if (dataList == null || dataList.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 构建返回结果
        List<NeSalesPurchaseVO> resultList = new ArrayList<>();
        
        for (NeProdoperSalesPurchase data : dataList) {
            NeSalesPurchaseVO vo = new NeSalesPurchaseVO();
            vo.setYear(data.getYear());
            vo.setMonth(data.getMonth());
            vo.setPurchasePower(data.getPurchasePower());
            resultList.add(vo);
        }
        //        升序
//        resultList.sort(Comparator.comparing(NeSalesPurchaseVO::getYear,NeSalesPurchaseVO::getMonth));
        return resultList;
    }

}
